<template>
  <Form class="my-form" ref="models_add" :model="value" :rules="rules" inline>
    <div class="my-form-item" >
      <slot :model="buffer">
        {{buffer}}
      </slot>
    </div>
    <div class="btn_box">
      <Button type="primary" @click="commit">提交</Button>
      <Button type="warning" @click="refresh">重置</Button>
      <Button type="error" @click="cancle">取消</Button>
      <slot name="commit"></slot>
    </div>
  </Form>
</template>
<script>
import { Promise } from 'q';
export default {
  name:'addForm',
  props: {
    value: {
      desc:'表单默认值',
      type: [Object,String],
      default: () => {
        return {};
      }
    },
    rules: {
      desc:'验证规则，支持 Promise',
      type: Object,
      default: () => {
        return {};
      }
    },
    api: {
      desc:'异步接口对象 { add:Promise }',
      type:Object,
      required:true,
    },
    format: {
      desc:'添加前格式化,参数为表单值对象',
      type: Function,
    }
  },
  data() {
    return {
      buffer: this.value
    };
  },
  methods: {
    commit() {
      this.$refs["models_add"].validate(valid => {
        if (valid) {
          this.$Message.success("验证成功!");
          this.format && this.format(this.buffer);
          this.api.add({
            model: {
              ...this.value
            }
          }).then(res => {
            this.refresh();
            this.$Message.success("添加成功!");
            this.$emit("success", res);
          }).catch(err => {
            this.$Message.error("添加失败!");
            this.$emit("fail", this.value);
          });
        } else {
          this.$Message.error("验证失败!");
          this.$emit("fail", this.value);
        }
      });
    },
    refresh() {
      this.$refs["models_add"].resetFields();
    },
    cancle() {
      this.$Message.info("取消操作!");
      this.$emit("cancle", this.value);
    }
  }
};
</script>

